package utils.wechat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import models.SystemParams;
import play.cache.Cache;
import services.SystemParamService;
import services.WeChatService;
import vos.weChat.TokenVo;

public class MenuUtil {
	private static final SimpleDateFormat dateTimeFormater = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	/**
	 * 获取实时token 
	 *
	 * @Title: getAccess_token 
	 * @param APPID
	 * @param APPSECRET
	 * @return
	 * @return: TokenVo
	 */
	private static TokenVo getAccess_token(String APPID,String APPSECRET){  
         
	         String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
	         String accessToken = null;
	         String expires_in=null;
	         TokenVo vo=new TokenVo();
	         try {
	                URL urlGet = new URL(url);
	                HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();    
	                  
	                http.setRequestMethod("GET");      //必须是get方式请求    
	                http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
	                http.setDoOutput(true);        
	                http.setDoInput(true);
	                System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
	                System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
	                http.connect();
	                InputStream is =http.getInputStream();
	                int size =is.available();
	                byte[] jsonBytes =new byte[size];
	                is.read(jsonBytes);
	                String message=new String(jsonBytes,"UTF-8");
	                JSONObject demoJson = JSON.parseObject(message);
	                accessToken = demoJson.getString("access_token");
	                expires_in=demoJson.getString("expires_in");
	                vo=new TokenVo(accessToken,expires_in);
	                vo.tokentime=dateTimeFormater.format(new Date());
	                /**
	                 * 更新缓存和数据库
	                 */
//	 			    String tokvo=JSON.toJSONString(vo);
//	 			    Cache.add("weChat_token", tokvo);
//	 			    SystemParams param=new SystemParams("wechat_token",tokvo,"");
//	 			    SystemParamService.saveParam(param);
            } catch (Exception e) {
                e.printStackTrace();
            }
	           return vo;
	        }
	     
	    /**
	     * 创建Menu
	    * @Title: createMenu
	    * @Description: 创建Menu
	    * @param @return
	    * @param @throws IOException    设定文件
	    * @return int    返回类型
	    * @throws
	     */
	    public static String createMenu(String token) {
	      String menu = "{\"button\":[{\"type\":\"view\",\"name\":\"进入管理\",\"url\":\"http://org.weijihealth.com/login.html\"}]}]}";
	         
	        //此处改为自己想要的结构体，替换即可
	       // String token= getAccessToken(APPID,APPSECRET);
	        String action = " https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+token;
	        try {
	           URL url = new URL(action);
	           HttpURLConnection http =   (HttpURLConnection) url.openConnection();    
	           http.setRequestMethod("POST");        
	           http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");    
	           http.setDoOutput(true);        
	           http.setDoInput(true);
	           System.setProperty("sun.net.client.defaultConnectTimeout", "30000");//连接超时30秒
	           System.setProperty("sun.net.client.defaultReadTimeout", "30000"); //读取超时30秒
	 
	           http.connect();
	           OutputStream os= http.getOutputStream();    
	           os.write(menu.getBytes("UTF-8"));//传入参数    
	           os.flush();
	           os.close();
	         
	           InputStream is =http.getInputStream();
	           int size =is.available();
	           byte[] jsonBytes =new byte[size];
	           is.read(jsonBytes);
	           String message=new String(jsonBytes,"UTF-8");
	           return message;
	           } catch (MalformedURLException e) {
	               e.printStackTrace();
	           } catch (IOException e) {
	               e.printStackTrace();
	           }    
	        return "createMenu 失败";
	   }
	   /**
	    * 获取token
	    * @param aPPSECRET 
	    * @param aPPID 
	    * @Title: getAccessToken 
	    * @return: void
	    */
	   public static String getAccessToken(String aPPID, String aPPSECRET){
		   TokenVo vo=WeChatService.getTokenByCache();
		   if(vo==null){
			   vo=getAccess_token(aPPID,aPPSECRET);
		   }
		   else{
			   Date date=new Date();
			   String tokentime=vo.tokentime;
			   Date tokTime=null;
			   try {
				   tokTime=dateTimeFormater.parse(tokentime);
				   long value=(date.getTime()-tokTime.getTime())/1000;
				   if(value>Long.parseLong(vo.expiresin)){
					   vo=getAccess_token(aPPID,aPPSECRET);
				   }
			   } catch (ParseException e) {
					// TODO Auto-generated catch block
				   e.printStackTrace();
			   }
		   }
		return vo.token;   
		   
	   }
	   public static void main(String[] args) {
		   TokenVo vo=getAccess_token("wxf3b5da1a81339a61","312ac7d4e561c994ba453c733cbfee0e");
		   String token=vo.token;
		   String message="{\"touser\":\""+"gh_afb47975290f"+",\"msgtype\":\"text\",\"text\":{\"content\":\"现在客服已下班，给您带来不便请谅解\"}}";
		   System.out.println(message);
		   String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+token;
		   String msg=HttpUtil.doPost(url, message);
		   System.out.println(msg);
	}
}
